package com.ws.action;

import com.ws.common.util.BeanUtils;
import com.ws.domain.dto.UserDTO;
import com.ws.domain.vo.UserVO;
import com.ws.entity.User;
import com.ws.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by WS on 2018/1/23.
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @PostMapping()
    public void saveUser(@RequestBody UserDTO userDTO){
        userService.insertUser(BeanUtils.copyBean(userDTO, User.class));
    }

    @GetMapping
    public List<UserVO> queryUserList(UserDTO userDTO){
        List<User> userDTOList = userService.queryUserList(BeanUtils.copyBean(userDTO, User.class));
        List<UserVO> userVOList = new ArrayList<>();
        for (User user : userDTOList) {
            UserVO userVO = BeanUtils.copyBean(user, UserVO.class);
            userVOList.add(userVO);
        }
        return userVOList;
    }

    @GetMapping("/userPage")
    public Map<String,Object> queryUserPage(UserDTO userDTO){
        Pageable pageable = new PageRequest(1,3);
        Page<User> page = userService.queryUserPage(BeanUtils.copyBean(userDTO, User.class), pageable);
        Map returnMap = new HashMap();
        returnMap.put("list",page.getContent());
        returnMap.put("total",page.getTotalElements());
        return returnMap;
    }

    @Autowired
    private UserService userService;
}
